package com.yuxiang.flowable.controller;

import com.yuxiang.flowable.result.BaseResult;
import com.yuxiang.flowable.result.CommonResult;
import com.yuxiang.flowable.util.Oss;
import com.yuxiang.flowable.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : yx-0176
 * @description
 * @date : 2022/3/9
 */
@RestController
@RequestMapping("/v1/file")
@Slf4j
public class FileController {

    @Value("${oss.bucketName}")
    private String bucket;

    @Value("${oss.previewUrl}")
    private String preUrl;

    @Value("${oss.packageName}")
    private String packageName;


    /**
     *  上传文件
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public BaseResult uploadFile(MultipartFile uploadFile) throws Exception {

        String fileUrl = OssUtil.uploadFile(uploadFile.getInputStream(), uploadFile.getOriginalFilename(), packageName, bucket);
        String url = preUrl + fileUrl;
        return CommonResult.buildData(url);
    }

    /**
     *  多文件上传文件
     * @param uploadFiles
     * @return
     * @throws Exception
     */
    @PostMapping("/upload/files")
    public BaseResult uploadFiles(MultipartFile uploadFiles) throws Exception {
        String fileUrl = OssUtil.uploadFile(uploadFiles.getInputStream(), uploadFiles.getOriginalFilename(), packageName, bucket);
        String url = preUrl + fileUrl;
        return CommonResult.buildData(url);
    }


    /**
     *  下载文件
     * @param req
     * @param response
     * @throws Exception
     */
    @GetMapping("/downloadFile")
    public void downloadFiles(HttpServletRequest req, HttpServletResponse response,String fileUrl) throws Exception {
        String substring = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
        String ossFile = fileUrl.replace(preUrl, "");
        // 获取Object，返回结果为OSSObject对象
        Oss.downloadObject(req, response, bucket, ossFile, substring);

    }


    /**
     *  下载多个文件为 zip
     */
    @PostMapping("/download2zip")
    public void downForZip(HttpServletRequest req, HttpServletResponse response){
        try {
            List<Map<String, String>> keyList= new ArrayList<>();
            Oss.downloadMultiObject2Zip(bucket, keyList, req, response, System.currentTimeMillis() + "简历.zip");
        } catch (IOException e) {
            log.error("FileController downForZip() error");
            throw new RuntimeException("下载简历失败");
        }

    }

}
